package org.jeecg.modules.sxaq.receiver;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.annotation.RabbitComponent;
import org.jeecg.modules.sxaq.anr.entity.RecordAbnormal;
import org.jeecg.modules.sxaq.anr.service.IRecordAbnormalService;
import org.jeecg.modules.sxaq.deviceinfo.entity.DeviceInfo;
import org.jeecg.modules.sxaq.deviceinfo.service.IDeviceInfoService;
import org.jeecg.modules.sxaq.utils.RabbitMQConstant;
import org.jeecg.modules.sxaq.utils.SmsUtils;
import org.jeecg.modules.sxaq.utils.jpush.JiGuangPushService;
import org.jeecg.modules.sxaq.utils.jpush.JpushUtils;
import org.jeecg.modules.sxaq.utils.jpush.PushBean;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDevice;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDeviceService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 登录处理
 * @Author: DHC
 * @Date: 2020-12-01
 */
@Slf4j
@RabbitComponent(value = "localLoginListener")
public class LoginRabbitMqListener {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysUserDeviceService sysUserDeviceService;


    @Autowired
    private IDeviceInfoService deviceInfoService;

    @Autowired
    private IRecordAbnormalService recordAbnormalService;

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private JpushUtils jpushUtils;
    @Autowired
    private SmsUtils smsUtils;

    @RabbitListener(concurrency = "2-10", bindings = {@QueueBinding(value = @Queue(value = RabbitMQConstant.LOCAL_LOGIN_QUEUE + "${sxaq.factoryCode}", durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = RabbitMQConstant.LOCAL_LOGIN_EXCHANGE, type = "topic"),
            key = RabbitMQConstant.LOCAL_LOGIN_KEY + "${sxaq.factoryCode}")})
    public void onMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {

//        jpushUtils.push("卸载核心文件(APP)", "112312321|||132t12636217356127", null);

        log.info("-------收到来自云端的登录操作下发-------");
        try {
            JSONObject object = JSONObject.parseObject(message);
            String type = object.getString("type");
            String workNo = object.getString("workNo");
            String phone = object.getString("phone");
            if ("login".equals(type)) {
                SysUser user = sysUserService.getUserByWorkNo(workNo);
                if (user != null) {
                    String mobileSingle = object.getString("mobileSingle");
                    String mobileVersion = object.getString("mobileVersion");
                    String mobileSystem = object.getString("mobileSystem");
                    String mobileModel = object.getString("mobileModel");
                    String appIdentifier = object.getString("appIdentifier");
                    String pushToken = object.getString("pushToken");
                    String clientType = object.getString("clientType");

                    // 根据工号和设备标识查询
                    SysUserDevice sysUserDevice = sysUserDeviceService.querySysUserDevice(workNo, mobileSingle);
                    if (sysUserDevice == null) {
                        // 为空新创建
                        sysUserDevice = new SysUserDevice();
                        sysUserDevice.setPushToken(pushToken);
                        sysUserDevice.setClientType(clientType);
                        sysUserDevice.setWorkNo(workNo);
                        sysUserDevice.setMobileSingle(mobileSingle);
                        sysUserDevice.setMobileModel(mobileModel);
                        sysUserDevice.setMobileVersion(mobileVersion);
                        sysUserDevice.setCreateTime(new Date());
                    } else {
                        // 不为空，更新token
                        sysUserDevice.setPushToken(pushToken);
                        sysUserDevice.setClientType(clientType);
                    }
                    sysUserDevice.setUpdateTime(new Date());
                    sysUserDeviceService.saveOrUpdate(sysUserDevice);

                    DeviceInfo deviceInfo = deviceInfoService.getDeviceBySingle(mobileSingle);
                    if (deviceInfo == null) {
                        DeviceInfo info = new DeviceInfo();
                        info.setMobileModel(mobileModel);
                        info.setMobileVersion(mobileVersion);
                        info.setMobileSystem(mobileSystem);
                        info.setMobileSingle(mobileSingle);
                        info.setAppIdentifier(appIdentifier);
                        deviceInfoService.save(info);
                    } else {
                        String oldAppIdentifier = deviceInfo.getAppIdentifier();
                        if (!oldAppIdentifier.equals(appIdentifier)) {
                            // 数据库的记录和app传递的不一致，代表app被删除，生成异常记录
                            RecordAbnormal recordAbnormal = new RecordAbnormal();
                            recordAbnormal.setType(9);
                            recordAbnormal.setPhone(user.getPhone());
                            recordAbnormal.setRealname(user.getRealname());
                            recordAbnormal.setSysOrgCode(user.getOrgCode());
                            recordAbnormal.setUsername(user.getUsername());
                            recordAbnormal.setUserId(user.getId());
                            recordAbnormal.setAnrId(UUID.randomUUID() + "_" + workNo);
                            recordAbnormal.setWorkNo(workNo);
                            recordAbnormal.setEventTime(new java.util.Date(System.currentTimeMillis()));
                            recordAbnormal.setMobileModel(deviceInfo.getMobileModel());
                            recordAbnormal.setMobileSystem(deviceInfo.getMobileSystem());
                            recordAbnormal.setMobileVersion(deviceInfo.getMobileVersion());
                            recordAbnormal.setMobileSingle(deviceInfo.getMobileSingle());
                            recordAbnormalService.saveOrUpdate(recordAbnormal);
                            // 卸载后重新记录时间
                            deviceInfo.setAppIdentifier(appIdentifier);
                            deviceInfoService.updateById(deviceInfo);

                            String depart = sysDepartService.queryDepartNameTxtByOrgCode(user.getOrgCode());

                            String push_app = depart + "的" + recordAbnormal.getRealname() + "[" + workNo + "]" + "在进入保密区域后，发生" + "卸载程序(APP)" + "事件。请相关部门及时处理！";
                            jpushUtils.push("卸载程序(APP)", push_app, null);

                            String push_sms = depart + "的" + recordAbnormal.getRealname() + "[" + workNo + "]";
                            smsUtils.sendSms(push_sms, "卸载程序(APP)");
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.info("-------收到来自云端的登录操作下发------" + e);
        }
    }
}
